package com.zhao.pullparser;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zhao.pullparser.domain.City;

public class MainActivity extends Activity {
    private final String TAG = "MainActivity";
    ArrayList<City> cityList=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    /**
     * 点击按钮获取解析xml
     * @param v
     * @throws IOException
     */
    public void click(View v) {
        int type;
        InputStream is=getClassLoader()
                .getResourceAsStream("weather.xml");    //获取资源文件
        XmlPullParser xpp=Xml.newPullParser();          //得到xml pull解析器
        try {
            xpp.setInput(is, "gbk");
            type=xpp.getEventType();
            City city = null;
            while(type!=XmlPullParser.END_DOCUMENT){
                switch (type) {
                case XmlPullParser.START_TAG:
                    if(xpp.getName().equals("weather")){
                        cityList=new ArrayList<City>();
                    }else if(xpp.getName().equals("city")){
                        city=new City();
                    }else if(xpp.getName().equals("name")){
                        String name=xpp.nextText();
                        city.setName(name);
                    }else if(xpp.getName().equals("temp")){
                        String temp=xpp.nextText();
                        city.setTemp(temp);
                    }else if(xpp.getName().equals("pm")){
                        String pm=xpp.nextText();
                        city.setPm(pm);
                    }
                    break;
                case XmlPullParser.END_TAG:
                    if(xpp.getName().equals("city")){
                        cityList.add(city);
                    }
                    break;
                default:
                    break;
                }
                type=xpp.next();            //到下一个节点
            }
            display();
            
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void display(){
        for (City c : cityList) {
            LinearLayout ll=(LinearLayout)findViewById(R.id.ll_root);
            TextView tv=new TextView(MainActivity.this);
            tv.setText(c.toString());
            ll.addView(tv);
            Log.d(TAG, c.toString()); 
        }
    }
}
